import { defineStore } from "pinia";
import { FLICKER, TANK } from '@/utils/global'
import { usePlayerStore } from "./player";
import { useEnemyStore } from './enemy'
import { useProtectionStore } from "./protection";

export const useFlickerStore = defineStore('flicker', {
  state: () => ({
    flickers: new Map(),
    id: 0
  }),
  actions: {
    bornFlicker(identity, position) {
      const o = {
        id: `flicker${this.id}`,
        index: 0,
        prog: 0,
        position, // keys of TANK.position
        identity, // enemy or player
        x: TANK.position[position].x,
        y: TANK.position[position].y,
      }

      this.flickers.set(o.id, o)
      this.id++
    },
    playFlicker(ft) {
      this.flickers.forEach(v => {
        if (v.prog >= FLICKER.process[v.index].dur) {
          if (v.index >= FLICKER.process.length - 1) {
            this.flickers.delete(v.id)
            if (v.identity === 'enemy') {
              const enemyStore = useEnemyStore()
              // 生成enemy TODO
            } else if (v.identity === 'player') {
              const playerStore = usePlayerStore()
              const protectionStore = useProtectionStore()
              const role = v.position === 'player1' ? 1 : 2
              playerStore.bornPlayer(role)
              protectionStore.bornProtection(role)
            }
          } else {
            this.flickers.set(v.id, { ...v, prog: 0, index: v.index + 1 })
          }
        } else {
          this.flickers.set(v.id, { ...v, prog: v.prog + ft })
        }
      })
    },
  }
})